package com.lzxzjy.web.servlet;

import com.alibaba.fastjson.JSON;
import com.lzxzjy.pojo.Admin;
import com.lzxzjy.pojo.PageBean;
import com.lzxzjy.serivce.AdminService;
import com.lzxzjy.serivce.impl.AdminServiceImpl;
import com.lzxzjy.util.EncryptionUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/admin/*")
public class AdminServlet extends BaseServlet {
    private final AdminService adminService = new AdminServiceImpl();

    public void getUserNme(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String adminName = (String) session.getAttribute("adminName");
        response.getWriter().write(adminName);
    }

    public void insertAdmin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader adminReader = request.getReader();
        String adminLine = adminReader.readLine();
        Admin admin = JSON.parseObject(adminLine, Admin.class);
        admin.setAdminState(1);
        admin.setAdminPassword(EncryptionUtil.encrypt(admin.getAdminPassword()));
        if (admin.isEmpty()) {
            response.getWriter().write("empty");
            return;
        }
        boolean isSuccess = false;
        try {
            isSuccess = adminService.insertAdmin(admin);
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry '") && e.getMessage().contains("' for key 'tb_admin.uk_admin_email'")) {
                response.getWriter().write("email");
                return;
            }
        }
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    private int[] toIntArrayAdminIds(String adminLine) {
        Admin[] admins = JSON.parseObject(adminLine, Admin[].class);
        StringBuilder stringAdminIds = new StringBuilder("[");
        for (Admin admin : admins) {
            stringAdminIds.append(admin.getAdminId());
            stringAdminIds.append(",");
        }
        stringAdminIds.replace(stringAdminIds.length() - 1, stringAdminIds.length(), "]");
        return JSON.parseObject(String.valueOf(stringAdminIds), int[].class);
    }

    public void deleteAdminByAdminIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader adminReader = request.getReader();
        String adminLine = adminReader.readLine();
        int[] adminIds = toIntArrayAdminIds(adminLine);
        boolean isSuccess = adminService.deleteAdminByIds(adminIds);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    public void deleteAdminByAdminId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int adminId = Integer.parseInt(request.getParameter("adminId"));
        String adminName = adminService.selectAdminByPageAndTerms(new Admin(adminId, "%%", "%%", "%%", null, "%%"), 0, 1).getRows().get(0).getAdminName();
        boolean isSuccess = adminService.deleteAdminById(adminId);
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    private int getAdminState(String adminStateValue) {
        if ("true".equals(adminStateValue)) {
            return 1;
        } else if ("false".equals(adminStateValue)) {
            return 0;
        }
        return -1;
    }

    public void updateAdminByAdminId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader adminReader = request.getReader();
        String adminLine = adminReader.readLine();
        Admin admin = JSON.parseObject(adminLine, Admin.class);

        String adminStateValue = request.getParameter("adminStateValue");
        if (getAdminState(adminStateValue) != -1) {
            admin.setAdminState(getAdminState(adminStateValue));
        }
        admin.setAdminPassword(EncryptionUtil.encrypt(admin.getAdminPassword()));
        boolean isSuccess = false;
        try {
            isSuccess = adminService.updateAdminById(admin);
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry '") && e.getMessage().contains("' for key 'tb_admin.uk_admin_email'")) {
                response.getWriter().write("email");
                return;
            }
        }
        if (isSuccess) {
            response.getWriter().write("success");
        } else {
            response.getWriter().write("failure");
        }
    }

    public void selectAdminByPageAndTerms(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader adminReader = request.getReader();
        String adminLine = adminReader.readLine();
        int currentPage = Integer.parseInt(request.getParameter("currentPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        Admin admin = JSON.parseObject(adminLine, Admin.class);
        admin.setAdminName("%" + admin.getAdminName() + "%");
        admin.setAdminEmail("%" + admin.getAdminEmail() + "%");
        admin.setAdminPassword("%" + admin.getAdminPassword() + "%");
        admin.setAdminPhone("%" + admin.getAdminPhone() + "%");
        PageBean<Admin> adminPageBean = adminService.selectAdminByPageAndTerms(admin, currentPage, pageSize);
        for (Admin ad : adminPageBean.getRows()) {
            ad.setAdminPassword(EncryptionUtil.decrypt(ad.getAdminPassword()));
        }
        String adminPageBeanLine = JSON.toJSONString(adminPageBean);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(adminPageBeanLine);
    }
}
